// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    // 初始化所有功能
    initNavigation();
    initScrollEffects();
    initFormHandling();
    initAnimations();
});

// 导航功能
function initNavigation() {
    const navToggle = document.querySelector('.nav-toggle');
    const navMenu = document.querySelector('.nav-menu');
    const header = document.querySelector('.header');

    // 移动端菜单切换
    if (navToggle && navMenu) {
        navToggle.addEventListener('click', function () {
            navMenu.classList.toggle('active');
            navToggle.classList.toggle('active');
        });
    }

    // 平滑滚动到锚点
    const navLinks = document.querySelectorAll('a[href^="#"]');
    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);

            if (targetElement) {
                const headerHeight = header.offsetHeight;
                const targetPosition = targetElement.offsetTop - headerHeight;

                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });

                // 关闭移动端菜单
                if (navMenu.classList.contains('active')) {
                    navMenu.classList.remove('active');
                    navToggle.classList.remove('active');
                }
            }
        });
    });

    // 滚动时改变导航栏样式
    window.addEventListener('scroll', function () {
        if (window.scrollY > 100) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
    });
}

// 滚动效果
function initScrollEffects() {
    // 添加滚动监听器来激活导航菜单项
    const sections = document.querySelectorAll('section[id]');
    const navLinks = document.querySelectorAll('.nav-menu a[href^="#"]');

    window.addEventListener('scroll', function () {
        let current = '';
        const scrollPosition = window.scrollY + 200;

        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;

            if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
                current = section.getAttribute('id');
            }
        });

        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === '#' + current) {
                link.classList.add('active');
            }
        });
    });

    // 滚动到顶部按钮
    createScrollToTopButton();
}

// 创建回到顶部按钮
function createScrollToTopButton() {
    const scrollTopBtn = document.createElement('button');
    scrollTopBtn.innerHTML = '↑';
    scrollTopBtn.className = 'scroll-top-btn';
    scrollTopBtn.style.cssText = `
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 50px;
        height: 50px;
        border: none;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        font-size: 20px;
        cursor: pointer;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
        z-index: 1000;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    `;

    document.body.appendChild(scrollTopBtn);

    // 滚动显示/隐藏按钮
    window.addEventListener('scroll', function () {
        if (window.scrollY > 500) {
            scrollTopBtn.style.opacity = '1';
            scrollTopBtn.style.visibility = 'visible';
        } else {
            scrollTopBtn.style.opacity = '0';
            scrollTopBtn.style.visibility = 'hidden';
        }
    });

    // 点击回到顶部
    scrollTopBtn.addEventListener('click', function () {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 表单处理
function initFormHandling() {
    const contactForm = document.querySelector('.contact-form form');

    if (contactForm) {
        contactForm.addEventListener('submit', function (e) {
            e.preventDefault();

            // 获取表单数据
            const formData = new FormData(this);
            const data = {};

            // 收集表单字段
            const inputs = this.querySelectorAll('input, select, textarea');
            inputs.forEach(input => {
                if (input.name || input.placeholder) {
                    const fieldName = input.name || input.placeholder;
                    data[fieldName] = input.value;
                }
            });

            // 验证表单
            if (!validateForm(data)) {
                return;
            }

            // 显示提交中状态
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '提交中...';
            submitBtn.disabled = true;

            // 模拟提交处理（实际项目中替换为真实的API调用）
            setTimeout(() => {
                showMessage('感谢您的咨询！我们将在24小时内与您取得联系。', 'success');
                contactForm.reset();
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }, 2000);
        });
    }
}

// 表单验证
function validateForm(data) {
    const requiredFields = ['您的姓名', '联系电话', '机构名称', '学员人数'];

    for (let field of requiredFields) {
        if (!data[field] || data[field].trim() === '') {
            showMessage(`请填写${field}`, 'error');
            return false;
        }
    }

    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(data['联系电话'])) {
        showMessage('请输入正确的手机号码', 'error');
        return false;
    }

    return true;
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageEl = document.createElement('div');
    messageEl.className = `message message-${type}`;
    messageEl.textContent = message;
    messageEl.style.cssText = `
        position: fixed;
        top: 100px;
        right: 30px;
        padding: 15px 25px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        animation: slideInRight 0.3s ease;
        max-width: 300px;
        word-wrap: break-word;
    `;

    // 设置背景色
    switch (type) {
        case 'success':
            messageEl.style.background = 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)';
            break;
        case 'error':
            messageEl.style.background = 'linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%)';
            break;
        default:
            messageEl.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
    }

    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        @keyframes slideOutRight {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(style);

    document.body.appendChild(messageEl);

    // 3秒后自动移除
    setTimeout(() => {
        messageEl.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.parentNode.removeChild(messageEl);
            }
        }, 300);
    }, 3000);
}

// 动画效果
function initAnimations() {
    // 简单的观察者API实现淡入动画
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function (entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.animation = 'fadeInUp 0.6s ease forwards';
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);

    // 需要动画的元素
    const animateElements = document.querySelectorAll(`
        .industry-category,
        .advantage-item,
        .feature-item,
        .product-card,
        .testimonial-item,
        .contact-form,
        .contact-info
    `);

    // 添加动画样式
    const animationStyle = document.createElement('style');
    animationStyle.textContent = `
        .industry-category,
        .advantage-item,
        .feature-item,
        .product-card,
        .testimonial-item,
        .contact-form,
        .contact-info {
            opacity: 0;
            transform: translateY(30px);
        }
        
        @keyframes fadeInUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    `;
    document.head.appendChild(animationStyle);

    // 观察所有需要动画的元素
    animateElements.forEach(el => {
        observer.observe(el);
    });
}

// 数字计数动画
function animateCounter(element, start, end, duration) {
    let startTimestamp = null;
    const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        const current = Math.floor(progress * (end - start) + start);
        element.textContent = current.toLocaleString();
        if (progress < 1) {
            window.requestAnimationFrame(step);
        }
    };
    window.requestAnimationFrame(step);
}

// 当统计数据进入视口时触发计数动画
const statsObserver = new IntersectionObserver(function (entries) {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const statItems = entry.target.querySelectorAll('.stat-item h3');
            statItems.forEach((item, index) => {
                const values = [500, 100000, 99]; // 对应的数值
                const finalValue = values[index];
                animateCounter(item, 0, finalValue, 2000);
            });
            statsObserver.unobserve(entry.target);
        }
    });
});

// 观察统计数据部分
const statsSection = document.querySelector('.about-stats');
if (statsSection) {
    statsObserver.observe(statsSection);
}

// 添加一些交互增强
document.addEventListener('DOMContentLoaded', function () {
    // 为产品卡片添加点击效果
    const productCards = document.querySelectorAll('.product-card');
    productCards.forEach(card => {
        card.addEventListener('click', function () {
            const btn = this.querySelector('.btn');
            if (btn) {
                btn.click();
            }
        });
    });

    // 为功能卡片添加hover效果
    const featureItems = document.querySelectorAll('.feature-item');
    featureItems.forEach(item => {
        item.addEventListener('mouseenter', function () {
            this.style.transform = 'translateY(-10px) scale(1.02)';
        });

        item.addEventListener('mouseleave', function () {
            this.style.transform = 'translateY(-5px) scale(1)';
        });
    });

    // 为行业标签添加点击跳转效果
    const industryTags = document.querySelectorAll('.industry-tag');
    industryTags.forEach(tag => {
        tag.addEventListener('click', function () {
            // 跳转到详细行业介绍部分
            const industriesSection = document.querySelector('.industries-section');
            if (industriesSection) {
                const headerHeight = document.querySelector('.header').offsetHeight;
                const targetPosition = industriesSection.offsetTop - headerHeight;

                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });

                // 添加高亮效果
                const clickedIndustry = this.textContent.trim();
                setTimeout(() => {
                    const categories = document.querySelectorAll('.industry-category');
                    categories.forEach(category => {
                        const categoryTitle = category.querySelector('h3').textContent.trim();
                        if (categoryTitle === clickedIndustry) {
                            category.style.animation = 'highlight 1s ease';
                            setTimeout(() => {
                                category.style.animation = '';
                            }, 1000);
                        }
                    });
                }, 500);
            }
        });
    });
});

// 添加键盘导航支持
document.addEventListener('keydown', function (e) {
    // ESC键关闭移动端菜单
    if (e.key === 'Escape') {
        const navMenu = document.querySelector('.nav-menu');
        const navToggle = document.querySelector('.nav-toggle');
        if (navMenu && navMenu.classList.contains('active')) {
            navMenu.classList.remove('active');
            navToggle.classList.remove('active');
        }
    }
});

// 确保页面SEO友好 - 添加结构化数据
function addStructuredData() {
    const structuredData = {
        "@context": "https://schema.org",
        "@type": "SoftwareApplication",
        "name": "永久免费教培机构管理系统",
        "description": "专业的教培机构管理系统，永久免费版支持100学员+10教师，提供CRM客户管理、智能排课、家长小程序、财务管理等完整功能，无隐藏费用",
        "applicationCategory": "EducationApplication",
        "operatingSystem": "Web",
        "offers": [
            {
                "@type": "Offer",
                "name": "基础版",
                "price": "0",
                "priceCurrency": "CNY",
                "description": "永久免费版本，支持100学员+10教师"
            },
            {
                "@type": "Offer",
                "name": "旗舰版",
                "price": "399",
                "priceCurrency": "CNY",
                "description": "专业版本，无限制使用"
            }
        ],
        "features": [
            "永久免费版本",
            "CRM客户管理",
            "智能排课系统",
            "家长小程序",
            "财务管理",
            "考勤签到",
            "教师工作台"
        ]
    };

    const script = document.createElement('script');
    script.type = 'application/ld+json';
    script.textContent = JSON.stringify(structuredData);
    document.head.appendChild(script);
}

// 页面加载完成后添加结构化数据
window.addEventListener('load', addStructuredData);

// 功能对比表折叠/展开功能
function toggleComparison() {
    const expandableContent = document.querySelector('.expandable-content');
    const btn = document.querySelector('.comparison-toggle-btn');
    const toggleText = document.querySelector('.toggle-text');

    if (expandableContent.classList.contains('collapsed')) {
        // 展开
        expandableContent.classList.remove('collapsed');
        expandableContent.classList.add('expanded');
        btn.classList.add('expanded');
        toggleText.textContent = '收起高级功能';

        // 展开后不需要滚动，保持当前位置
    } else {
        // 收起
        expandableContent.classList.remove('expanded');
        expandableContent.classList.add('collapsed');
        btn.classList.remove('expanded');
        toggleText.textContent = '展开全部功能对比';
    }
} 